# coding: utf-8
"""
日志记录
=======

"""
import logging
from django.utils import timezone


class ApplicationLogs(object):
    def __init__(self, name):
        self.log = logging.getLogger(name)

    def info(self, msg, *args, **kwargs):
        self.log.info(self.add_time_str(msg), *args, **kwargs)

    def error(self, msg, *args, **kwargs):
        self.log.error(self.add_time_str(msg), *args, **kwargs)

    @staticmethod
    def add_time_str(msg):
        return '{0}:{1}'.format(timezone.localtime().strftime('%Y-%m-%d %H:%M:%S'), msg)


class LogDetail(object):
    """
    日志信息类
    """

    def __init__(self):
        self.base = {}
        self.values = {}

    def set_values(self, d):
        if not isinstance(d, dict):
            raise Exception("LogDetail.set_values() need a dict param, not a {0}".format(str(type(d))))
        self.values = d

    def set_key_value(self, k, v):
        self.values[k] = v

    def get_values(self):
        return self.values

    def set_base(self, description=None, module=None, class_name=None, function=None):
        self.base = {
            "description": description,
            "module": module,
            "class": class_name,
            "function": function
        }

    def initial(self, obj):
        function = obj.action if hasattr(obj, "action") else None
        self.reset()
        self.set_base(module=obj.__module__, class_name=obj.__class__.__name__, function=function)

    def reset(self):
        self.base = {}
        self.values = {}

    def get_base(self):
        return self.base

    def set_description(self, v):
        self.base["description"] = v

    def get_description(self):
        return self.base.get("description", None)

    def set_module(self, v):
        self.base["module"] = v

    def set_class(self, v):
        self.base["class"] = v

    def set_function(self, v):
        self.base["function"] = v

    def to_format_string(self):
        """
        生成格式化的异常信息字符串
        :return:
        """
        detail = self.base.get("description", None)
        module = self.base.get("module", None)
        class_name = self.base.get("class", None)
        function = self.base.get("function", None)

        base = "{0}; Module:{1}; Class:{2}; Function:{3};".format(detail, module, class_name, function)

        info = ""

        if self.values:
            for key in self.values.keys():
                info += " {0}:{1};".format(key, self.values[key])

        string = base + info

        return string


def log_error():
    return ApplicationLogs('app.error.log')


def log_running():
    return ApplicationLogs('app.running.log')


def log_worker():
    return ApplicationLogs('django.channels.worker')
